--local sku_key = KEYS --skuId
--local buy_quantity = ARGV --购买数量
--local skuInventory = "ProductInventory:"
--
--for i = 1, #sku_key do
--
--    local exists = redis.call("EXISTS",skuInventory ..sku_key[i]);
--    local inventory = redis.call("GET",skuInventory ..sku_key[i]);
--
--    if exists == 0 then
--        inventory = 0
--    end
--
--    if buy_quantity[i] > inventory then
--        return 1
--    else
--        redis.call("DECRBY",skuInventory ..sku_key[i],buy_quantity[i])
--        return tonumber(inventory)
--    end
--
--end




local sku_key = KEYS -- skuId
local buy_quantity = ARGV -- 购买数量
local skuInventory = "ProductInventoryLhc:"

for i = 1, #sku_key do
    local key = skuInventory .. sku_key[i]
    local exists = redis.call("EXISTS", key)
    if exists == 0 then
        return exists -- 键不存在，返回错误
    end
    local inventory = tonumber(redis.call("GET", key)) or 0

    -- 检查购买数量是否为 nil 或非数字
    if not buy_quantity[i] or tonumber(buy_quantity[i]) == nil then
        return 3 -- 购买数量无效，返回错误
    end

    if tonumber(buy_quantity[i]) > inventory then
        return inventory -- 库存不足，返回错误
    end
end

-- 所有SKU库存都足够，开始减少库存
for i = 1, #sku_key do
    local key = skuInventory .. sku_key[i]
    redis.call("DECRBY", key, buy_quantity[i])
end

return 0 -- 成功减少库存





--local current_stock = tonumber(redis.call('GET', sku_key))  --当前库存
--
--if not current_stock then
--    return 0
--end
--
--if current_stock and current_stock>=buy_quantity then
--    redis.call('DECRBY',sku_key,buy_quantity)
--    return 1
--else
--    return 2
--end
